package cn.good.yan.b11;

/**
 * b11  比较器 Comparable
 *     案例 一个实体  需要 implements Comparable
 * @author shengren.yan
 * @create 2023-07-30
 */
public class TPojo implements Comparable{

    private String name;
    private Integer age;

    public TPojo() {

    }

    public TPojo(String name, Integer age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    /**
     * 重写该方法 - 排序的逻辑
     * (如果返回的对象是正数，当前对象大)
     * (如果返回的对象是负数，当前对象小)
     * (如果返回的对象是0，一样大)
     *
     * @param o o
     * @return int
     */
    @Override
    public int compareTo(Object o) {
        // 代表是当前对象
        if (o == this) {
            return 0;
        }
        // 先比age ，再比较name
        if (o instanceof TPojo) {
            TPojo p = (TPojo) o;
            int compare = Integer.compare(this.age, p.age);
            if (compare != 0) {
                return  compare;    //  (从小到大)
//                return - compare; // (从大到小)
            }
            return this.name.compareTo(p.name);
        }
        throw new RuntimeException("类型不对");
//        return 0;
    }

    @Override
    public String toString() {
        return "TPojo{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}
